package com.ray.system.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.AppBuilder;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.check.AppCheck;
import com.ray.system.service.SysAppService;
import com.ray.system.table.dto.AppQueryDTO;
import com.ray.system.table.entity.SysApp;
import com.ray.system.table.params.app.AppCreateParams;
import com.ray.system.table.params.app.AppEditParams;
import com.ray.system.table.params.app.AppQueryParams;
import com.ray.system.table.vo.app.AppVO;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 应用相关服务
 * @Class: AppApi
 * @Package com.ray.system.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class AppApi {

    @Autowired
    private SysAppService sysAppService;


    /**
     * 查询应用列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<AppVO>> pageApps(CommonPage<AppQueryParams, Page<AppVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<AppQueryDTO, SysApp> commonPageBuilder = new CommonPageBuilder<>(AppQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<SysApp> page = sysAppService.page(commonPageBuilder.bulid(), loginUser);
        List<SysApp> apps = page.getRecords();
        //结果对象
        IPage<AppVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotEmpty(apps)) {
            pageList.setRecords(apps.stream().map(sysApp -> {
                AppVO appVO = new AppVO();
                BeanUtil.copyProperties(sysApp, appVO);
                return appVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }

    /**
     * 查询应用列表信息--启用的应用
     *
     * @param queryParams
     * @return
     */
    public Result<List<AppVO>> queryApps(AppQueryParams queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        AppQueryDTO queryDTO = new AppQueryDTO();
        BeanUtil.copyProperties(queryParams, queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<SysApp> Apps = sysAppService.list(queryDTO, loginUser);
        //查询对象
        List<AppVO> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(Apps)) {
            list = Apps.stream().map(sysApp -> {
                AppVO AppVO = new AppVO();
                BeanUtil.copyProperties(sysApp, AppVO);
                return AppVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }


    /**
     * 创建应用
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createApp(AppCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断AppKey是否存在
        SysApp sysApp = sysAppService.queryAppByAppKey(createParams.getAppKey());
        new AppCheck(sysApp).checkAppKey(null,SysMsgCodeConstant.Error.ERR10000003);
        AppBuilder AppBuilder = new AppBuilder();
        AppBuilder.append(createParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //保存应用信息
        if (!sysAppService.save(AppBuilder.bulid())) {
            log.info("保存应用接口异常,参数:{}", JSON.toJSONString(AppBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, AppBuilder.getCode());
    }

    /**
     * 编辑应用
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editApp(AppEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //判断AppKey是否存在
        SysApp sysApp = sysAppService.queryAppByAppKey(editParams.getAppKey());
        new AppCheck(sysApp).checkAppKey(editParams.getAppCode(),SysMsgCodeConstant.Error.ERR10000003);
        AppBuilder AppBuilder = new AppBuilder();
        AppBuilder.append(editParams).appendEdit(loginUser);
        //编辑应用信息
        if (!sysAppService.edit(AppBuilder.bulid(), loginUser)) {
            log.info("编辑应用接口异常,参数:{}", JSON.toJSONString(AppBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, AppBuilder.getCode());
    }


    /**
     * 删除应用
     *
     * @param appCode 应用编码
     * @return Result
     */
    @Transactional
    public Result<String> deleteApp(String appCode) {
        ValidateUtil.hasLength(appCode,"参数[appCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysApp sysApp = sysAppService.queryAppByAppCode(appCode, loginUser);
        new AppCheck(sysApp).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        AppBuilder AppBuilder = new AppBuilder();
        AppBuilder.appendCode(appCode).appendEdit(loginUser).delete();
        //删除应用信息
        if (!sysAppService.edit(AppBuilder.bulid(), loginUser)) {
            log.info("删除应用接口异常,参数:{}", JSON.toJSONString(AppBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, AppBuilder.getCode());
    }

    /**
     * 开启应用
     *
     * @param appCode 应用编码
     * @return Result
     */
    @Transactional
    public Result<String> openApp(String appCode) {
        ValidateUtil.hasLength(appCode,"参数[appCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysApp sysApp = sysAppService.queryAppByAppCode(appCode, loginUser);
        new AppCheck(sysApp).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        AppBuilder AppBuilder = new AppBuilder();
        AppBuilder.appendCode(appCode).appendEdit(loginUser).open();
        //开启应用信息
        if (!sysAppService.edit(AppBuilder.bulid(), loginUser)) {
            log.info("开启应用接口异常,参数:{}", JSON.toJSONString(AppBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, AppBuilder.getCode());
    }

    /**
     * 开启应用
     *
     * @param appCode 应用编码
     * @return Result
     */
    @Transactional
    public Result<String> closeApp(String appCode) {
        ValidateUtil.hasLength(appCode,"参数[appCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysApp sysApp = sysAppService.queryAppByAppCode(appCode, loginUser);
        new AppCheck(sysApp).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        AppBuilder AppBuilder = new AppBuilder();
        AppBuilder.appendCode(appCode).appendEdit(loginUser).close();
        //关闭应用信息
        if (!sysAppService.edit(AppBuilder.bulid(), loginUser)) {
            log.info("关闭应用接口异常,参数:{}", JSON.toJSONString(AppBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, AppBuilder.getCode());
    }

    /**
     * 应用详情
     *
     * @param appCode 应用编码
     * @return Result
     */
    public Result<AppVO> viewApp(String appCode) {
        ValidateUtil.hasLength(appCode,"参数[appCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysApp sysApp = sysAppService.queryAppByAppCode(appCode, loginUser);
        new AppCheck(sysApp).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        AppVO AppVO = new AppVO();
        BeanUtil.copyProperties(sysApp, AppVO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, AppVO);
    }


}
